package com.example.unique

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.GeocodeQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener
import com.google.android.gms.maps.model.LatLng

class MapSelection2Activity : AppCompatActivity() {

    private lateinit var locationClient: AMapLocationClient
    private lateinit var tvLocationStatus: TextView
    private lateinit var etAddress: EditText
    private lateinit var radius: EditText
    private lateinit var btnSearchAddress: Button
    private lateinit var btnBack: Button
    private lateinit var geocodeSearch: GeocodeSearch
    private lateinit var targetLocation : LatLng
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map_selection2)
        // 设置隐私合规
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)
        // 初始化 UI 组件
        tvLocationStatus = findViewById(R.id.tv_location_status)
        etAddress = findViewById(R.id.et_address)
        radius = findViewById(R.id.radius)
        btnSearchAddress = findViewById(R.id.btn_search_address)
        btnBack = findViewById(R.id.back)

        // 请求定位相关的权限
        requestPermissions(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ), 1
        )

        // 初始化地理编码服务
        geocodeSearch = GeocodeSearch(this)
        geocodeSearch.setOnGeocodeSearchListener(object : OnGeocodeSearchListener {
            override fun onGeocodeSearched(result: GeocodeResult?, rCode: Int) {
                if (rCode == 1000 && result != null && result.geocodeAddressList.isNotEmpty()) {
                    val latLngPoint = result.geocodeAddressList[0].latLonPoint
                    val latitude = latLngPoint.latitude
                    val longitude = latLngPoint.longitude
                    targetLocation=LatLng(latitude,longitude)
                    Toast.makeText(this@MapSelection2Activity, "地址经纬度: $latitude, $longitude", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this@MapSelection2Activity, "未找到指定地址", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {}
        })

        // 查询按钮点击事件
        btnSearchAddress.setOnClickListener {
            val address = etAddress.text.toString()
            if (address.isNotEmpty()) {
                getLatLngFromAddress(address)
            } else {
                Toast.makeText(this, "请输入有效地址", Toast.LENGTH_SHORT).show()
            }
        }

        // 返回按钮点击事件
        btnBack.setOnClickListener {
            val address = etAddress.text.toString()
            val radiusValue = radius.text.toString().toDoubleOrNull() ?: 0.0

            // 将位置信息和范围存储在 Intent 中
            val data = Intent().apply {
                putExtra("address", address)
                putExtra("radius", radiusValue)
            }

            // 设置结果并结束 Activity
            setResult(666, data)
            finish()
        }

        // 开始定位
        startLocation()
    }

    // 启动定位
    private fun startLocation() {
        locationClient = AMapLocationClient(applicationContext)
        locationClient.setLocationListener(locationListener)

        val locationOption = AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            isNeedAddress = true
            isMockEnable = true
        }
        locationClient.setLocationOption(locationOption)

        // 开始定位
        locationClient.startLocation()
        Log.d("MapSelectionActivity", "开始定位")
    }

    // 定位监听器
    private val locationListener = AMapLocationListener { location ->
        if (location != null && location.errorCode == 0) {
            val locationInfo = "当前位置: ${location.city} ${location.district} ${location.street} ${location.streetNum}"
            tvLocationStatus.text = locationInfo
        } else {
            Log.e("MapSelectionActivity", "定位失败，错误码：${location.errorCode}, 错误信息：${location.errorInfo}")
            Toast.makeText(this, "定位失败，请检查权限设置", Toast.LENGTH_SHORT).show()
        }
    }

    // 获取指定地址的经纬度
    private fun getLatLngFromAddress(address: String) {
        val query = GeocodeQuery(address, "")
        geocodeSearch.getFromLocationNameAsyn(query)
    }

    override fun onDestroy() {
        locationClient.stopLocation()
        locationClient.onDestroy()
        super.onDestroy()
    }
}
